<link rel="stylesheet" href="${base}/assets/plugins/codemirror/lib/codemirror.css">
<link rel="stylesheet" href="${base}/assets/plugins/codemirror/theme/seti.css">
<link rel="stylesheet" href="${base}/assets/plugins/codemirror/addon/fold/foldgutter.css"/>
<link rel="stylesheet" href="${base}/assets/plugins/bootstrap-fileinput/css/fileinput.min.css"/>
<link rel="stylesheet" href="${base}/assets/css/customizerform.css">
<div class="page page-full bg-white animation-fade">
    <div class="page-aside">
        <div class="page-aside-switch">
            <i class="icon wb-chevron-left" aria-hidden="true"></i>
            <i class="icon wb-chevron-right" aria-hidden="true"></i>
        </div>
        <div class="page-aside-inner height-full" data-toggle="slimScroll">
            <div class="page-aside-section">
                <h5 class="page-aside-title">系统模块</h5>
                <div id="sys_menu_Tree" class="ztree" style="padding: 10px 20px;"></div>
            </div>
        </div>
    </div>
    <div class="page-main">
        <div class="page-header">
            <h1 class="page-title">表单设计</h1>
            <div class="page-header-actions">
                <a class="btn btn-primary" href="#" onclick="Page.FormGenerator.createIndex()">
                    <i class="fa fa-plus"></i> 生成模块首页
                </a>
                <a class="btn btn-primary" href="#" onclick="Page.FormGenerator.openGeneratorFormConfig()">
                    <i class="fa fa-plus"></i> 导入表单
                </a>

            </div>
        </div>
        <div class="page-content" >
            <div class="tabbable tabs-below">
                <div class="tab-content">
                    <div ole="tabpanel" class="tab-pane in active fade" id="one_">
                        <textarea id="code" realName="code"></textarea>
                    </div>
                    <div class="tab-pane fade" id="two_">
                        <div class="ibox float-e-margins">
                            <div class="ibox-title">
                                <h5>拖拽左侧表单元素到此区域</h5>
                                <div class="ibox-tools">
                                    请选择显示的列数：
                                    <select id="n-columns">
                                        <option value="1">显示1列</option>
                                        <option value="2">显示2列</option>
                                    </select>
                                        <button id="generate" type="button" class="btn btn-primary btn-block">生成代码</button>

                                </div>
                            </div>

                            <div class="ibox-content" style="height:350px">
                                <div class="row form-body form-horizontal m-t" style="height: 100%;">
                                    <div id="customizer-container" class="col-md-12 droppable sortable ui-droppable ui-sortable clearfloat"  style="height: 100%;">
                                    </div>
                                    <div class="col-md-6 droppable sortable ui-droppable ui-sortable" style="display: none;"></div>
                                    <div class="col-md-6 droppable sortable ui-droppable ui-sortable" style="display: none;"></div>
                                </div>

                            </div>
                        </div>
                    </div>
                </div>
                <ul class="nav nav-tabs" user="tablist">
                    <li class="active" ><a href="#one_"  aria-controls="one_" user="tab" data-toggle="tab">代码</a></li>
                    <li><a href="#two_" aria-controls="two_" user="tab" data-toggle="tab">设计</a></li>
                </ul>
            </div>
        </div>
    </div>

    <div class="site-action">

        <button type="button" class="site-action-toggle btn-raised btn btn-success btn-floating">
            <i class="fa fa-wrench animation-scale-up" data-toggle="tooltip" data-placement="left" title="操作"></i>
            <i class="fa fa-close animation-scale-up hidden" data-toggle="tooltip" data-placement="left" title="关闭"></i>
        </button>
        <div class="site-action-buttons">
            <button type="button" id="import" class="btn-raised btn btn-success btn-floating " data-toggle="tooltip"
                    data-placement="left" title="导入">
                <i class="fa fa-external-link" aria-hidden="true"></i>
            </button>

            <button type="button" id="reload" class="btn-raised btn btn-success btn-floating " data-toggle="tooltip"
                    data-placement="left" title="刷新">
                <i class="fa fa-refresh" aria-hidden="true"></i>
            </button>

            <button type="button" id="back" class="btn-raised btn btn-success btn-floating " data-toggle="tooltip"
                    data-placement="left" title="返回">
                <i class="fa fa-mail-reply" aria-hidden="true"></i>
            </button>
        </div>
    </div>
</div>

<div id="app-customizer" class="app-customizer">
    <a href="javascript:void(0)" onclick="setup_draggable()" class="app-customizer-toggle theme-color" data-toggle="class" data-class="open"
       data-active="false" data-target="#app-customizer">
        <i class="fa fa-gear"></i>
    </a>
    <div class="customizer-tabs" style="padding:10px 10px">
        <div id="customizer-form" class="customizer-form clearfloat" style="visibility: hidden;">
            <div class="lr-custmerform-component" data-type="label">
                <i class="fa fa-font"></i>标 题
            </div>
            <div class="lr-custmerform-component" data-type="html">
                <i class="fa fa-file-o"></i>富文本
            </div>
            <div class="lr-custmerform-component" data-type="text">
                <i class="fa fa-italic"></i>文本框
            </div>
            <div class="lr-custmerform-component" data-type="textarea">
                <i class="fa fa-align-justify"></i>文本区
            </div>
            <div class="lr-custmerform-component" data-type="texteditor">
                <i class="fa fa-edit"></i>编辑器
            </div>
            <div class="lr-custmerform-component" data-type="radio">
                <i class="fa fa-circle-thin"></i>
                单选框
            </div>
            <div class="lr-custmerform-component" data-type="checkbox">
                <i class="fa fa-square-o"></i>多选框
            </div>
            <div class="lr-custmerform-component" data-type="select">
                <i class="fa fa-caret-square-o-right"></i>下拉框
            </div>
            <div class="lr-custmerform-component" data-type="datetime">
                <i class="fa fa-calendar"></i>日期框
            </div>
            <div class="lr-custmerform-component" data-type="datetimerange">
                <i class="fa fa-calendar"></i>日期区间
            </div>
            <div class="lr-custmerform-component" data-type="encode">
                <i class="fa fa-barcode"></i>编 码
            </div>
            <div class="lr-custmerform-component" data-type="organize">
                <i class="fa fa-coffee"></i>单位组织
            </div>
            <div class="lr-custmerform-component" data-type="currentInfo">
                <i class="fa fa-book"></i>当前信息
            </div>
            <div class="lr-custmerform-component" data-type="guid">
                <i class="fa fa-info"></i>GUID
            </div>
            <div class="lr-custmerform-component" data-type="upload">
                <i class="fa fa-paperclip"></i>附件上传
            </div>
            <div class="lr-custmerform-component" data-type="girdtable">
                <i class="fa fa-table"></i>编辑表格
            </div>
        </div>
    </div><!-- .customizer-taps -->

</div>


<script src="${base}/assets/plugins/codemirror/lib/codemirror.js" data-realName="codemirror"></script>
<script src="${base}/assets/js/jquery-ui.min.js"></script>
<script type="text/javascript" data-deps="codemirror">
    $.namespace('Page.FormGenerator');

    Page.FormGenerator = function () {
        var setting = {
            async: {
                enable: true,
                url: "${base}/admin/sys/menu/getTree",
                autoParam: ["id", "realName=n", "level=lv"],
            },

            check: {enable: "" == "true", nocheckInherit: true},
            view: {selectedMulti: false, dblClickExpand: false},
            callback: {
                onClick: function (event, treeId, treeNode) {
                    Page.FormGenerator.selectNode = treeNode;
                    Page.FormGenerator.readFormConfig();
                },
                onDblClick: function () {

                }
            }
        }, SysMenuTree, selectNode, editor;
        return {
            init: function () {
                Page.FormGenerator.bindKey();
                setTimeout(function() {
                    Page.FormGenerator.crateAction();
                    Page.FormGenerator.SysMenuTree = $.fn.zTree.init($("#sys_menu_Tree"), setting)
                    Page.FormGenerator.createCodeEditer()
                    Page.FormGenerator.generateCode();

                },660)
            },
            bindKey:function(){
                $(window).bind('keydown', function(event) {
                    if (event.ctrlKey || event.metaKey) {
                        switch (String.fromCharCode(event.which).toLowerCase()) {
                            case 's':
                                event.preventDefault();
                                Page.FormGenerator.doImport();
                                break;
                            case 'r':
                                event.preventDefault();
                                Page.FormGenerator.reload();
                                break;

                        }
                    }
                });
            },
            crateAction: function () {
                $('.site-action-toggle').on('click', function () {
                    $but = $(this);
                    $('.site-action-buttons').animate({
                        opacity: "toggle",
                        height: "toggle"
                    }, 200);
                    $but.find('i').toggle();
                })

                $('#import').on('click', function () {
                    Page.FormGenerator.doImport();
                })
                $('#reload').on('click', function () {
                    Page.FormGenerator.reload();
                })
                $('#back').on('click', function () {
                    Bolt.navtab('switchTab', 'main')
                })
            },
            reload:function () {
                Bolt.ajax('doajax', {
                        data: {modulePath: Page.FormGenerator.selectNode.path},
                        url: '${base}/admin/sys/code_generator/reloadFormConfig',
                        loadingMask: true
                });
            },

            createCodeEditer: function () {
                var height = document.documentElement.clientHeight - 200 + "px";
                Page.FormGenerator.editor = CodeMirror.fromTextArea(document.getElementById("code"), {
                    mode: "text/x-java", //实现Java代码高亮
                    lineNumbers: true,	//显示行号
                    theme: "seti",	//设置主题
                    lineWrapping: true,//代码折叠
                    matchBrackets: true	//括号匹配
                });
                Page.CodeGenerator.editor.setSize('auto', height);
            },
            readFormConfig: function () {
                Bolt.ajax('doajax', {
                    data: {modulePath: Page.FormGenerator.selectNode.path},
                    url: '${base}/admin/sys/code_generator/readFormConfig',
                    loadingMask: true,
                    okCallback: function (content) {
                        if ( typeof(content) == "string"  ) {
                            Page.FormGenerator.editor.setValue(content);
                            Page.FormGenerator.editor.setSize(null, 400);
                        } else {
                            Bolt.notify("warning", "不存在表单配置，请生成导入");
                        }
                    }
                });

            },
            openGeneratorFormConfig: function () {
                if (!Page.FormGenerator.selectNode) {
                    Bolt.notify("warning", "请选择模块");
                    return;
                }
                var modulePath = Page.FormGenerator.selectNode.path, moduleTitle = Page.FormGenerator.selectNode['realName'];
                if (!modulePath) {
                    Bolt.notify("warning", "模块未配置URL不能操作");
                    return;
                }
                $(this).dialog({
                    title: "表单配置",
                    modalSize:'modal-lg',
                    url: '${base}/admin/sys/code_generator/generatorFormConfig?modulePath=' + modulePath + "&moduleTitle=" + moduleTitle
                });
            },
            createIndex: function () {
                if (!Page.FormGenerator.selectNode) {
                    Bolt.notify("warning", "请选择模块");
                    return;
                }
                var modulePath = Page.FormGenerator.selectNode.path, moduleTitle = Page.FormGenerator.selectNode['realName']
                $(this).dialog({
                    title: "生成首页",
                    url: '${base}/admin/sys/code_generator/indexConfigForm?modulePath=' + modulePath + "&moduleTitle=" + moduleTitle
                });
            },
            doImport: function () {
                var sourceData = {
                    code: Page.FormGenerator.editor.getValue(),
                    modulePath: Page.FormGenerator.selectNode.path
                }
                Bolt.ajax('doajax', {
                    data: sourceData,
                    confirmMsg: "已经存在会覆盖原文,请谨慎操作.",
                    url: '${base}/admin/sys/code_generator/generatorFormFile',
                    loadingMask: true
                })
            },
            generateCode:function () {
                $("#generate").click(function () {
                    var submitArr=[];
                    if($("#customizer-container").children().length){
                        $("#customizer-container").children().each(function(i,n){
//               console.log(i);console.log(n.dataset);
                            if(n.dataset.field){
                                submitArr.push(JSON.parse(n.dataset.field));
                            }else{
                                toastr.warning("请对第"+(i+1)+"个表单添加配置参数!");
                                return false;
                            }
                        });
                        console.log(submitArr);
                    }else{
                        toastr.warning("请添加表单设计!");
                    }
                });
            }
        }
    }();

    var setup_draggable = function () {
        var $self,validateArr=['不能为空！'];

        if($("ul[user='tablist']>li").eq(1).hasClass('active')){
        $("#customizer-form").css("visibility","visible");

        function getLabel(val){
            return '<div class="lr-compont-title fl" ><span>'+val+'</span> <i class="del  fr">╳</i></div><div class="lr-compont-value fl">'+val+'</div><div class="clear"></div>'
        }
        $("#customizer-form>div").draggable({
            helper:function(ui){
                return '<div style="width:200px;height:40px;padding-left:15px;line-height:40px;background:#fff;border: 1px solid #eeecec;border-radius:4px;">'+$(ui.currentTarget).html()+'</div>'
            },
            connectToSortable:'#customizer-container',
            containment:'#customizer-container'
        });

        $("#customizer-container").sortable({

            forcePlaceholderSize:true,
            placeholder: "sortable-placeholder",
            appendTo: '#customizer-container',
            start:function(){
                $("div.sortable-placeholder").html("拖放控件到这里");
            }
        });

        $("#customizer-container").droppable({

            drop:function(event,ui){
                var labelindex = ui.draggable.text().trim().indexOf('╳'),label;

                if(labelindex>-1){
                    label=ui.draggable.text().trim().substring(0,labelindex)
                }else{
                    label=ui.draggable.text().trim()
                }

                ui.draggable.html(getLabel(label)).appendTo(this);
                label=null;
            }
        });

        $("#customizer-container").on('click','div.lr-custmerform-component',function(){
            $(this).addClass('active').siblings().removeClass('active');
            var datatype = $(this)[0].dataset.type;
            $(this).popover({
                placement:'bottom',
                trigger:'manual',
                delay: {show: 10, hide: 10},
                html: true,
                title: function () {
                    return '配置参数';
                },
                content: function () {
                    return '<form class="layui-form">' +
                        '<div class="layui-form-item">' +
                        '<label class="layui-form-label">组件标题</label>' +
                        '<div class="layui-input-block">' +
                        '<input type="text" realName="title"  class="layui-input">' +
                        '</div>' +
                        '</div>' +
                        '<div class="layui-form-item">' +
                        '<label class="layui-form-label">字段验证</label>' +
                        '<div class="layui-input-block">' +
                        '<select class="layui-select" realName="validate">' +
                        '<option value="0">不能为空！</option>' +
                        '</select>' +
                        '</div>' +
                        '</div>' +
                        '<div class="layui-form-item">' +
                        '<label class="layui-form-label">所占行比例</label>' +
                        '<div class="layui-input-block">' +
                        '<select class="layui-select" realName="width">' +
                        '<option value="1">1</option>' +
                        '<option value="2">1/2</option>' +
                        '<option value="3">1/3</option>' +
                        '<option value="4">1/4</option>' +
                        '</select>' +
                        '</div>' +
                        '</div>' +
                        '<div class="layui-form-item">' +
                        '<label class="layui-form-label">是否只读</label>' +
                        '<div class="layui-input-block">' +
                        '<select class="layui-select" realName="updateOnlyRead">' +
                        '<option value="true">只读</option>' +
                        '<option value="false">可写</option>' +
                        '</select>' +
                        '</div>' +
                        '</div>' +
                        '<div class="layui-form-item" style="text-align:center;">' +
                        '<button type="button" class="btn btn-primary btnyes">确认</button>' +
                        '<button type="button" class="btn btn-warning btnno">取消</button></div>' +
                        '</form>';

                }
            });
            $self = $(this);
            $(this).popover('show').siblings("div.lr-custmerform-component").popover('hide');
        });
        $("#customizer-container").on('click','form.layui-form button.btnyes',function(){
            var newjson={};
            ($("form.layui-form").serializeArray()).forEach(function (item) {
                if(item.realName=="validate"){
                    newjson[item.realName]=validateArr[item.value];
                }else if(item.realName=="width"){
                    newjson[item.realName]=1/(item.value)*100+'%';
                    $self.width(1/(item.value)*100+'%');
                }else if(item.realName=="title"){
                    newjson.label=item.value;
                    $self.find("div.lr-compont-title>span").text(item.value);
                    $self.find("div.lr-compont-value").text(item.value);
                    newjson.id=pinyinUtil.getFirstLetter(item.value)
                }else{
                    newjson[item.realName]=item.value;
                }
            });
            newjson.type=$self[0].dataset.type;
            $self[0].dataset.field=JSON.stringify(newjson);

            $self.popover('hide');
        });
        $("#customizer-container").on('click','form.layui-form button.btnno',function(){
            $self.popover('hide');
        });
        $("#customizer-container").on('click','i.del',function(){
            $(this).parents("div.lr-custmerform-component").remove();
        });

        }
    };
    $(document).ready(function () {
        Page.FormGenerator.init();
    });
</script>